//
//  UIView+TP_Utility.m
//  E_Car
//
//  Created by 谭鹏 on 2017/4/12.
//  Copyright © 2017年 谭鹏. All rights reserved.
//

#import "UIView+TP_Utility.h"
#import <Masonry/Masonry.h>
#import "UIImage+TP_Utility.h"

#import <objc/runtime.h>
typedef void(^WillAnimatedHandle)();
typedef void(^AnimationsHandle)();
typedef void(^DidAnimatedHandle)();

#ifndef SCREAN_HEIGHT
#define SCREAN_HEIGHT [UIScreen mainScreen].bounds.size.height
#endif

#ifndef SCREAN_WIDTH
#define SCREAN_WIDTH [UIScreen mainScreen].bounds.size.width
#endif
//runtime 属性key
static char imgView_blankViewKey;

static char willAnimatedHandleKey;
static char animationsHandleKey;
static char didAnimatedHandleKey;

@interface UIView()
@property UIImageView * imgView_blankView;

@property WillAnimatedHandle  willAnimatedHandle;//将要动画前block
@property AnimationsHandle animationsHandle;// 动画block
@property DidAnimatedHandle didAnimatedHandle;//动画结束后block

@end
@implementation UIView (TP_Utility)

-(void)addSubviews:(NSArray <UIView *> *)views{
    for (UIView * view in views) {
        [self addSubview:view];
    }
}
-(UIView *)subViewWithTag:(NSInteger)tag{
    for (UIView * subView in self.subviews) {
        if (subView.tag == tag) {
            return subView;
        }
    }
    return nil;
}

#pragma mark - get super viewcontroller
-(UIViewController *)getSuperViewController{
    for (UIView * view = self; view; view = view.superview) {
        UIResponder * nextResponder = [view nextResponder];
        if ([nextResponder isKindOfClass:[UIViewController class]]) {
            return (UIViewController *)nextResponder;
        }
    }
    return nil;
}
#pragma mark - get super view
-(UIView *)getSuperViewWithClass:(Class)class{
    for (UIView * view = self; view; view = view.superview) {
        UIResponder * nextResponder = [view nextResponder];
        if ([nextResponder isKindOfClass:class]) {
            return (UIView *)nextResponder;
        }
    }
    return nil;
}


-(void)setBlankBackgroundViewHiden:(BOOL)hiden{
    if (!self.imgView_blankView) {
        [self setBlankView];
    }
    
    [self.imgView_blankView setHidden:hiden];
}

-(void)setBlankView{
    self.imgView_blankView = [[UIImageView alloc]initWithImage:[UIImage imageNamed:@"Blank_Data"]];
    [self addSubview:self.imgView_blankView];
    [self.imgView_blankView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.center.mas_equalTo(self);
    }];
    
}
#pragma mark - animation
-(void)animatedWithScale:(CGFloat)scale willAnimatedHandle:(WillAnimatedHandle)willAnimatedHandle animationsHandle:(AnimationsHandle)animationsHandle didAnimatedHandleid:(DidAnimatedHandle)didAnimatedHandle{
    //先将文件夹那个视图进行截图
    UIImage *animationImage = [UIImage snapImageForView:self];
    UIImageView * animationImageView = [[UIImageView alloc]initWithImage:animationImage];
    // 再将文件夹视图的坐标系迁移到窗口坐标系（绝对坐标系）
    CGRect targetFrame_start = [self.superview convertRect:self.frame toView:nil];
    
    // 计算动画终点位置
    CGFloat targetW = targetFrame_start.size.width*scale;
    CGFloat targetH = targetFrame_start.size.height*scale;
    CGFloat targetX = 0;
    CGFloat targetY = 0;
    if (scale < 1) { //缩
        targetY = ((SCREAN_HEIGHT - targetH) / 2.0);
        targetX = ((SCREAN_WIDTH - targetW) / 2.0);
    }else if (scale < 2){ //1～2 倍 放大
        targetY = targetFrame_start.origin.y + targetFrame_start.size.height*(1-scale)/2;
        targetX = targetFrame_start.origin.x + targetFrame_start.size.width *(1-scale)/2;
    }else {//2 倍以上放大
        targetY = 0;
         targetX = ((SCREAN_WIDTH - targetW) / 2.0);
    }
    
    CGRect targetFrame_end = CGRectMake(targetX, targetY, targetW, targetH);
    
    // 添加做动画的元素
    if (!animationImageView.superview) {
        animationImageView.image = animationImage;
        animationImageView.frame = targetFrame_start;
        animationImageView.alpha = 1;
        [UIApplication.sharedApplication.keyWindow  addSubview:animationImageView];
    }
    //动画前block
    if (willAnimatedHandle) {
        willAnimatedHandle();
    }
    // 预览动画
    [UIView animateWithDuration:0.3 delay:0. options:UIViewAnimationOptionCurveEaseIn animations:^{
        
        animationImageView.frame = targetFrame_end;
        animationImageView.alpha = 0;
        if (animationsHandle) {
            animationsHandle();
        }
        
    } completion:^(BOOL finished) {
        [animationImageView removeFromSuperview];
        if (didAnimatedHandle) {
            didAnimatedHandle();
        }
    }];
}

//约束更新后 产生动画
- (void)animatedWithConstraintsUpdate{
    // 通知需要更新约束，但是不立即执行
    [self setNeedsUpdateConstraints];
    // 立即更新约束，以执行动态变换
    [self updateConstraintsIfNeeded];
    // 执行动画效果, 设置动画时间
    
    [UIView animateWithDuration:0.2 animations:^{
        [self layoutIfNeeded];
    }];
}
-(void)animatedFromeScale:(CGFloat)scale willAnimatedHandle:(WillAnimatedHandle)willAnimatedHandle animationsHandle:(AnimationsHandle)animationsHandle didAnimatedHandleid:(DidAnimatedHandle)didAnimatedHandle{
    //先将文件夹那个视图进行截图
    UIImage *animationImage = [UIImage snapImageForView:self];
    UIImageView * animationImageView = [[UIImageView alloc]initWithImage:animationImage];
    // 再将文件夹视图的坐标系迁移到窗口坐标系（绝对坐标系）
    CGRect targetFrame_end = [self.superview convertRect:self.frame toView:nil];
    
    // 计算动画期起点位置
    CGFloat targetW = targetFrame_end.size.width*scale;
    CGFloat targetH = targetFrame_end.size.height*scale;
    CGFloat targetX = 0;
    CGFloat targetY = 0;
    if (scale < 1) { //缩
        targetY = ((SCREAN_HEIGHT - targetH) / 2.0);
        targetX = ((SCREAN_WIDTH - targetW) / 2.0);
    }else if (scale < 2){ //1～2 倍 放大
        targetY = targetFrame_end.origin.y + targetFrame_end.size.height*(1-scale)/2;
        targetX = targetFrame_end.origin.x + targetFrame_end.size.width *(1-scale)/2;
    }else {//2 倍以上放大
        targetY = 0;
        targetX = ((SCREAN_WIDTH - targetW) / 2.0);
    }
    
    CGRect targetFrame_start = CGRectMake(targetX, targetY, targetW, targetH);
    
    // 添加做动画的元素
    if (!animationImageView.superview) {
        animationImageView.image = animationImage;
        animationImageView.frame = targetFrame_start;
        animationImageView.alpha = 0;
        [UIApplication.sharedApplication.keyWindow  addSubview:animationImageView];
    }
    //动画前block
    if (willAnimatedHandle) {
        willAnimatedHandle();
    }
    // 预览动画
    [UIView animateWithDuration:0.3 delay:0. options:UIViewAnimationOptionCurveEaseIn animations:^{
        
        animationImageView.frame = targetFrame_end;
        animationImageView.alpha = 1;
        if (animationsHandle) {
            animationsHandle();
        }
        
    } completion:^(BOOL finished) {
        [animationImageView removeFromSuperview];
        if (didAnimatedHandle) {
            didAnimatedHandle();
        }
    }];
}
#pragma mark - private
//利用rumtime 给 Catagory 设置属性
-(void)setImgView_blankView:(UIImageView *)imgView_blankView{
    objc_setAssociatedObject(self, &imgView_blankViewKey, imgView_blankView, OBJC_ASSOCIATION_RETAIN);
}
-(UIImageView *)imgView_blankView{
   return  objc_getAssociatedObject(self, &imgView_blankViewKey);
}

//willAnimatedHandle属性
-(void)setWillAnimatedHandle:(WillAnimatedHandle)willAnimatedHandle{
    objc_setAssociatedObject(self, &willAnimatedHandleKey, willAnimatedHandle, OBJC_ASSOCIATION_COPY);
};
-(WillAnimatedHandle)willAnimatedHandle{
    return objc_getAssociatedObject(self, &willAnimatedHandleKey);
}

-(void)setAnimationsHandle:(AnimationsHandle)animationsHandle{
    objc_setAssociatedObject(self, &animationsHandleKey, animationsHandle, OBJC_ASSOCIATION_COPY);
}
-(AnimationsHandle)animationsHandle{
    return objc_getAssociatedObject(self, &animationsHandleKey);
}

-(void)setDidAnimatedHandle:(DidAnimatedHandle)didAnimatedHandle{
    objc_setAssociatedObject(self, &didAnimatedHandleKey, didAnimatedHandle, OBJC_ASSOCIATION_COPY);
}
-(DidAnimatedHandle)didAnimatedHandle{
    return objc_getAssociatedObject(self, &didAnimatedHandleKey);
}


#pragma mark - set constraints


/**
 *  添加子视图并自动规则排列subView
 *
 *  @param childViews      将添加的子视图,如果已经添加会忽略，而且会全部重新排列
 *  @param colunm          列数
 *  @param childViewHeight =0，自适应, 且height都相同；=-1 不设置height;<-1 自计算，但是不设置height都相同；>0时，self.height 且height都相同 优先级大于 childViewHeight
 *  @param childViewWidth  =0，自适应, 且height都相同；<0 自适应，但是不设置height都相同；>0时，self.height 且height都相同 优先级大于 childViewHeight
 *  @param rowSpace        行间距,小于0时，自适应
 *  @param colunmSpace     列间距
 *  @param edgeInsets      内部间距
 */
-(void)setGridConstraintsWithChildViews:(NSArray<UIView *> *)childViews colunm:(NSUInteger)colunm childViewHeight:(CGFloat)childViewHeight childViewWidth:(CGFloat)childViewWidth rowSpace:(CGFloat)rowSpace colunmSpace:(CGFloat)colunmSpace edgeInsets:(UIEdgeInsets)edgeInsets {
    
    [self addSubviews:childViews];
    
    
    childViews = self.subviews;
    
    UIView * lastView = nil;
    __block UIView * firstColunmViewForRow = nil; //一行中的首个view
    __block CGSize  maxHeightSize = CGSizeZero;//一行中的最高高度
    //    UIView * lastSpaceView = nil;
    for (int i = 0; i < childViews.count; i ++) {
        
        UIView * view = childViews[i];
        
        if (view.tag == kViewTag_spaceView) {
            break;//跳入下个循环
        }
        //view内添加间距spaceView,spaceView位于childView右下角，用于判断间隔
        UIView * spaceView  =  [view subViewWithTag:kViewTag_spaceView];
        if (!spaceView ) {
            spaceView = [UIView new];
            spaceView.tag = kViewTag_spaceView;
            spaceView.backgroundColor = [UIColor clearColor];
            [view addSubview:spaceView];
            
            [spaceView mas_makeConstraints:^(MASConstraintMaker *make) {
                if(!lastView){
                    if (colunmSpace >= 0) {
                        make.width.mas_equalTo(colunmSpace);
                    }
                }else{
                    make.width.mas_equalTo([lastView subViewWithTag:kViewTag_spaceView]);
                }
                
                
                if(!lastView){
                    if (rowSpace>=0) {
                        make.height.mas_equalTo(rowSpace);
                    }
                }else{
                    make.height.mas_equalTo([lastView subViewWithTag:kViewTag_spaceView]);
                }
                
                make.left.mas_equalTo(view.mas_right);
                make.top.mas_equalTo(view.mas_bottom);
            }];
            
        }else{
            NSLog(@"spaceView 已经存在");
        }
        
        //----end----
        CGSize calculatedSize = [view sizeThatFits:CGSizeMake(childViewWidth>0?childViewWidth:CGFLOAT_MAX, childViewHeight>0?childViewHeight:CGFLOAT_MAX)];//计算出的高度 宽度
        
        //size
        [view mas_remakeConstraints:^(MASConstraintMaker *make) {
            
            
            if (i%colunm == 0) {//第一列
                firstColunmViewForRow = view;
                maxHeightSize = calculatedSize;
                
                if (childViewHeight > 0) {
                    make.height.mas_equalTo(childViewHeight);
                }else if(childViewHeight == 0){
                    if (lastView) {
                        make.height.mas_equalTo(lastView);
                    }
                    
                }else{
                    //                    make.height.mas_equalTo(calculatedSize.height);
                }
                
                if (childViewWidth >0) {
                    make.width.mas_equalTo(childViewWidth);
                }
                else if(childViewWidth == 0){
                    if (lastView) {
                        make.width.mas_equalTo(lastView);
                    }
                }
                
            }else{
                if (childViewHeight >= 0) {
                    make.height.mas_equalTo(lastView);
                }else{
                    
                    //                    make.height.mas_equalTo(lastView);
                }
                
                
                if (childViewWidth >= 0) {
                    make.width.mas_equalTo(lastView);
                }
                
                
            }
            
        }];
        
        if (childViewHeight < -1) {
            if (maxHeightSize.height < calculatedSize.height  ) {
                maxHeightSize = calculatedSize;
            }
            [firstColunmViewForRow mas_updateConstraints:^(MASConstraintMaker *make) {
                make.height.mas_equalTo(maxHeightSize.height);
            }];
        }
        [view mas_updateConstraints:^(MASConstraintMaker *make) {
            
            
            
            //位置
            if (i%colunm == 0) { //第一列
                make.left.mas_equalTo(self).offset(edgeInsets.left);
                
                if (i / colunm == 0) {//第一行
                    make.top.mas_equalTo(self).offset(edgeInsets.top);
                }else{//非第一行
                    make.top.mas_equalTo([childViews[i - colunm] subViewWithTag:kViewTag_spaceView].mas_bottom);
                }
                
            }else {//非第一列
                
                make.centerY.mas_equalTo(lastView);
                make.left.mas_equalTo([lastView subViewWithTag:kViewTag_spaceView].mas_right);
                
            }
            if (i%colunm == colunm - 1) {//最右侧 childView
                make.right.mas_equalTo(self).offset(-edgeInsets.right);
            }
            if (i == childViews.count - 1) {//最末一个 childView
                make.bottom.mas_equalTo(self).offset(-edgeInsets.bottom);
            }
            
        }];
        
        
        if (i%colunm == 0) {//第一列
            firstColunmViewForRow = view;
        }
        lastView = view;
    }
    
}



#pragma mark - 工厂 产生 view
+(UIView *)lineWithWidth:(CGFloat)width bgColor:(UIColor *)bgcolor isHorizonal:(BOOL)isHorizonal {
    UIView * line  = [UIView new];
    line.backgroundColor = bgcolor;
    
    [line mas_makeConstraints:^(MASConstraintMaker *make) {
        make.width.mas_equalTo(isHorizonal?MAXFLOAT:width).priorityLow();
        make.height.mas_equalTo(isHorizonal?width:MAXFLOAT).priorityLow();
    }];
    
    return line;
}

@end
